/**
 * 竞品分析页面逻辑
 *
 * @author AI Crawlers Team
 * @date 2025-10-10
 */

// 清理可能存在的旧图表实例
if (typeof competitorAnalysis !== 'undefined' && competitorAnalysis.charts) {
    try {
        Object.values(competitorAnalysis.charts).forEach(chart => {
            if (chart && typeof chart.dispose === 'function') {
                chart.dispose();
            }
        });
    } catch (e) {
        console.log('清理旧竞品分析图表:', e);
    }
}

var competitorAnalysis = {
    
    /**
     * 初始化
     */
    init() {
        this.loadOurProducts();
    },
    
    /**
     * 加载我方产品列表
     */
    async loadOurProducts() {
        try {
            const res = await productApi.getList({ 
                page: 1, 
                size: 100, 
                isOurProduct: 1,
                status: 1 
            });
            
            const products = res.data.list || [];
            
            // 填充下拉框
            const select = $('#selectOurProduct');
            select.empty();
            select.append('<option value="">请选择我方产品...</option>');
            
            products.forEach(p => {
                select.append(`
                    <option value="${p.productId}" 
                            data-name="${p.productName}"
                            data-brand="${p.brand || ''}"
                            data-category="${p.category || ''}"
                            data-price="${p.priceRange || ''}"
                            data-focus="${p.focusLevel || ''}">
                        ${p.productName} ${p.brand ? '(' + p.brand + ')' : ''}
                    </option>
                `);
            });
            
        } catch (error) {
            console.error('加载我方产品失败：', error);
            utils.error('加载产品列表失败');
        }
    },
    
    /**
     * 开始分析
     */
    async analyze() {
        const productId = $('#selectOurProduct').val();
        
        if (!productId) {
            utils.warning('请先选择我方产品');
            return;
        }
        
        try {
            utils.showLoading('分析中...');
            
            // 获取产品信息
            const selected = $('#selectOurProduct option:selected');
            const productInfo = {
                id: productId,
                name: selected.data('name'),
                brand: selected.data('brand'),
                category: selected.data('category'),
                price: selected.data('price'),
                focus: selected.data('focus')
            };
            
            // 获取竞品列表
            const res = await productApi.getCompetitors(productId);
            const competitors = res.data || [];
            
            utils.hideLoading();
            
            // 显示分析结果
            this.displayResult(productInfo, competitors);
            
        } catch (error) {
            utils.hideLoading();
            console.error('分析失败：', error);
            utils.error('分析失败');
        }
    },
    
    /**
     * 显示分析结果
     */
    displayResult(productInfo, competitors) {
        // 隐藏空状态，显示结果
        $('#emptyState').hide();
        $('#analysisResult').show();
        
        // 显示产品信息
        $('#productName').text(productInfo.name);
        $('#productBrand').text(productInfo.brand || '-');
        $('#productCategory').text(productInfo.category || '-');
        $('#productPrice').text(productInfo.price || '-');
        
        const focusMap = {
            'high': '<span class="badge bg-danger">重点关注</span>',
            'normal': '<span class="badge bg-info">一般关注</span>',
            'low': '<span class="badge bg-secondary">低关注</span>'
        };
        $('#productFocus').html(focusMap[productInfo.focus] || '-');
        
        // 统计竞品
        $('#competitorCount').text(competitors.length);
        
        const directCount = competitors.filter(c => c.competitor_type === 'direct').length;
        const indirectCount = competitors.filter(c => c.competitor_type === 'indirect').length;
        const highStrengthCount = competitors.filter(c => c.strength === 'high').length;
        
        $('#directCount').text(directCount);
        $('#indirectCount').text(indirectCount);
        $('#highStrengthCount').text(highStrengthCount);
        
        // 渲染竞品列表
        this.renderCompetitorTable(competitors);
    },
    
    /**
     * 渲染竞品表格
     */
    renderCompetitorTable(competitors) {
        const tbody = $('#competitorTableBody');
        tbody.empty();
        
        if (competitors.length === 0) {
            tbody.html('<tr><td colspan="7" class="text-center text-muted">暂无竞品配置</td></tr>');
            return;
        }
        
        const typeMap = {
            'direct': '<span class="badge bg-danger">直接竞品</span>',
            'indirect': '<span class="badge bg-warning">间接竞品</span>',
            'potential': '<span class="badge bg-info">潜在竞品</span>'
        };
        
        const strengthMap = {
            'high': '<span class="badge bg-danger">强</span>',
            'medium': '<span class="badge bg-warning">中</span>',
            'low': '<span class="badge bg-info">弱</span>'
        };
        
        competitors.forEach(comp => {
            const tr = $('<tr></tr>');
            tr.html(`
                <td><strong>${utils.escapeHtml(comp.productName)}</strong></td>
                <td>${utils.escapeHtml(comp.brand || '-')}</td>
                <td>${utils.escapeHtml(comp.priceRange || '-')}</td>
                <td>${typeMap[comp.competitor_type] || '-'}</td>
                <td>${strengthMap[comp.strength] || '-'}</td>
                <td>${utils.escapeHtml(comp.dimension || '-')}</td>
                <td>${utils.escapeHtml(comp.pc_remark || '-')}</td>
            `);
            tbody.append(tr);
        });
    }
};

// 页面加载完成后初始化
$(document).ready(function() {
    // 清理可能存在的旧图表实例
    if (competitorAnalysis.charts) {
        Object.values(competitorAnalysis.charts).forEach(chart => {
            if (chart && typeof chart.dispose === 'function') {
                try {
                    chart.dispose();
                } catch (e) {
                    console.log('销毁旧图表:', e);
                }
            }
        });
        competitorAnalysis.charts = {};
    }
    competitorAnalysis.init();
});

